//
//  CommodityDetailViewController.m
//  DuBai
//
//  Created by darktm on 14-2-25.
//  Copyright (c) 2014年 darktm. All rights reserved.
//

#import "CommodityDetailViewController.h"

#import "OrderDetailViewController.h"

#import "CommodityDetailBiddingCell.h"

#import "TaskWithGetGoodsDetail.h"
#import "TaskWithGetSales.h"
#import "TaskWithPrise.h"


#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"

#import "GoodsDetail.h"
#import "Sales.h"

@interface CommodityDetailViewController ()<WYHttpTaskDelegate,CommodityDetailMoreDelegate>

@property (nonatomic,strong)GoodsDetail *goodDetail;
@property (nonatomic,strong)NSMutableArray *salesArray;

@end

@implementation CommodityDetailViewController

#define kTagGoodsImages 10000

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.tableView.hidden = YES;
    [self loadGoodsDetail];
}

#pragma mark - tableview delegate -

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.salesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CommodityDetailBiddingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommodityDetailBiddingCell"];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"CommodityDetailBiddingCell" owner:self options:nil] objectAtIndex:0];
    }
    
    Sales *sale = self.salesArray[indexPath.row];
    cell.price.text = [@"RMB " stringByAppendingString:sale.price];
    cell.seles.text = sale.sales;
    
    if(indexPath.row == 0){
        cell.buy.hidden = NO;
        [cell.buy addTarget:self action:@selector(on_btn_sale_buy:) forControlEvents:UIControlEventTouchUpInside];
    }else{
        cell.buy.hidden = YES;
    }
    
    return cell;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - buy delegate -

-(void)commodityBuyBtn{
    OrderDetailViewController *order = (OrderDetailViewController*)[Utils storyBoardWithId:@"OrderDetailViewController"];
    order.goodid = self.goodDetail.id;
    [self.navigationController pushViewController:order animated:YES];
}


#pragma mark - http delegate -

-(void)requestCompleteWithObj:(WYHttpTask *)obj{
    
    id rsult = [obj parese];
    
    if([obj isKindOfClass:[TaskWithGetGoodsDetail class]]){
        
        if(!rsult){
            
            for (UIView *view in self.view.subviews) {
                [view removeFromSuperview];
            }
            
            UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
            label.text = @"商品不存在";
            label.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:label];
            
            self.title = label.text;
            
            return;
        }
        
        self.goodDetail = rsult;
        [self showGoodDetail];
        [self loadGoodSales];
    }else if ([obj isKindOfClass:[TaskWithGetSales class]]){
        
        self.salesArray = rsult;
        [self showSales];
    }else if([obj isKindOfClass:[TaskWithPrise class]]){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [Utils saveToLocalPlistForValue:self.goodDetail.id key:self.goodDetail.id];
        self.favouriteBtn.enabled = NO;
    }
    
}
-(void)requestFailWithMsg:(WYHttpTask *)obj{
    DLog(@"%@",obj.networkOp.url);
    
    if([obj isKindOfClass:[TaskWithPrise class]]){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }
}

#pragma mark - customer method -

-(void)loadGoodsDetail{
    TaskWithGetGoodsDetail *detail = [[TaskWithGetGoodsDetail alloc] init];
    detail.delegate = self;
    detail.goodid = self.goodid;
    [detail start];
}

-(void)loadGoodSales{
    TaskWithGetSales *sales = [[TaskWithGetSales alloc] init];
    sales.delegate = self;
    sales.goodid = self.goodDetail.id;
    [sales start];
}

-(void)prise{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    TaskWithPrise *prise = [[TaskWithPrise alloc] init];
    prise.delegate = self;
    prise.goodid = self.goodDetail.id;
    [prise start];
    
    self.netPrise = prise;
    
}

-(void)showGoodDetail{
    
    //加载更多
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CommodityDetailMore" owner:self options:nil];
    
    CommodityDetailMore *detaile = nib[0];
    CGRect frame = self.tableView.frame;
    detaile.delegate = self;
    detaile.frame = CGRectMake(0,frame.origin.y, 320, 670);
    
    [self.view addSubview:detaile];
    
    self.detailMore = detaile;
    self.srv.contentSize = CGSizeMake(320, frame.origin.y + 670);
    
    if([self.goodDetail.sales intValue] == 0){//没有开售
        self.imgOff.hidden = YES;
        self.tableView.hidden = YES;
    }
    
    [self refreshSrv];

    [self.detailMore configureInfo:self.goodDetail];
    
    self.title = self.goodDetail.name;
    self.commodityDesc.text = self.goodDetail.desc;
    self.imagesDes.text = self.goodDetail.desc;
    
    self.releaseTime.text = self.goodDetail.shelfTime;
    self.hots.text = self.goodDetail.hotNum;

    //本地判断时候有赞过
    
    if([Utils valueForLocalPlist:self.goodDetail.id])
        self.favouriteBtn.enabled = NO;
    
    self.commodityNum.text = self.goodDetail.code;
    self.leftTime.seconds = [self.goodDetail.endtime longLongValue] - [self.goodDetail.starttime longLongValue];

    [self.imagesBtn setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:self.goodDetail.shopimage]] forState:UIControlStateNormal];
}

-(void)showSales{
    
    CGRect frame = self.tableView.frame;
    frame.size.height = self.salesArray.count * 44;
    self.tableView.frame = frame;
    
    [UIView animateWithDuration:.25 animations:^{
        self.detailMore.frame = CGRectMake(0, frame.size.height + frame.origin.y, 320, 670);
    }];
    
    self.srv.contentSize = CGSizeMake(320, frame.size.height + frame.origin.y + 670);
    
    self.tableView.hidden = NO;
    
    [self.tableView reloadData];
}

//刷新广告
-(void)refreshSrv{
    
    int imagesCount = self.goodDetail.images.count;
    for (int i = 0; i < imagesCount; i++) {
        NSString *url = self.goodDetail.images[i];
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(i * 240, 0, 240, 128)];
        btn.tag = kTagGoodsImages + i;
        [btn setBackgroundImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:url]] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(on_btn_good_image:) forControlEvents:UIControlEventTouchUpInside];
        [self.imagesSrc addSubview:btn];
    }
    
    self.pageControl.numberOfPages = self.goodDetail.images.count;
    self.pageControl.currentPage = 0;
    self.pageControl.center = CGPointMake(self.imagesSrc.center.x, self.pageControl.center.y);
    
    self.imagesSrc.pagingEnabled = YES;
    self.imagesSrc.contentSize = CGSizeMake(240 * imagesCount, 1);
    
    if(imagesCount > 1){
        [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(on_timer_change_good_images:) userInfo:nil repeats:YES];
    }
}


#pragma mark - timer repeate -
-(void)on_timer_change_good_images:(NSTimer *)timer{
    
    int count = self.goodDetail.images.count;
    int cur = self.pageControl.currentPage;
    ++cur;
    cur = cur % count;
    self.pageControl.currentPage = cur;
    [self.imagesSrc setContentOffset:CGPointMake(240 * cur, 0) animated:YES];
}


#pragma mark - btn actions -


-(void)on_btn_sale_buy:(UIButton *)btn{
    DLog(@"%@",btn);
}

-(void)on_btn_good_image:(UIButton *)btn{
    DLog(@"%@",btn);
}


- (IBAction)on_btn_share:(UIButton *)sender {
}

- (IBAction)on_btn_favourite:(UIButton *)sender {
    [self prise];
}

- (IBAction)on_btn_more_image:(UIButton *)sender {
}

@end
